<template>
  <div>
    <el-row>
      <el-col :md="6" :sm="24" class="leftOrgTree">
        <el-card style="height: 100%">
          <cr-org-tree v-model="orgObj" :treeHeight="leftOrgTreeHeight"></cr-org-tree>
        </el-card>
      </el-col>
      <el-col :md="18" :sm="24">
        <div class="table-block">
          <el-card>
            <div slot="header" class="clearfix">
              <span class="left">角色列表</span>
              <div class="right">
                <div class="table-operator card-right">
                  <el-button type="primary" @click="addUserHandle()" size="mini" v-if="menuButtonPermissions.includes('permission.addOrgRole')">添加角色</el-button>
                  <el-button type="primary" size="mini" v-else style="visibility: hidden;">添加角色</el-button>

                </div>
              </div>
            </div>
            <el-table
              :data="roleTableList"
              row-key="id"
              stripe
              :height="tableMaxHeigth"
              highlight-current-row
              ref="roleTableListRef"
            >
              <el-table-column type="index" label="序号" align="center" width="50" />
              <el-table-column prop="roleName" label="角色名称" align="center" show-overflow-tooltip />
              <el-table-column prop="roleKey" label="角色key" align="center" show-overflow-tooltip />
              <el-table-column prop="roleType" label="角色类型" align="center" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.roleType === 1 ? '系统管理员' : '自定义' }}
                </template>
              </el-table-column>
              <el-table-column prop="roleType" label="操作" align="center" width="150">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    icon="el-icon-user"
                    @click="searchUserList(scope.row)"
                    class="table-button-size"
                    title="成员列表"
                  ></el-button>
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    @click="delRole(scope.row)"
                    v-if="menuButtonPermissions.includes('permission.delOrgRole')"
                    class="table-button-size"
                    title="移除角色"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              :total="roleTableListTotal"
              :page.sync="queryParams.pageNo"
              :limit.sync="queryParams.pageSize"
              @pagination="getTableList"
            />
          </el-card>
        </div>
        <div class="table-block">
          <el-card>
            <div slot="header" class="clearfix">
              <div class="left userList">
                <span style="margin-right: 10px">成员列表 </span>
                <el-radio-group v-model="radio1" border @change="radioGroup">
                  <el-radio-button :label="1">用户列表</el-radio-button>
                  <el-radio-button :label="2">组织列表</el-radio-button>
                </el-radio-group>
              </div>

              <div class="right">
                <div class="table-operator card-right">
                  <el-button
                    @click="batchDelete()"
                    :disabled="!(selectUserList.length || selectOrgList.length)"
                    size="mini"
                    v-if="menuButtonPermissions.includes('permission.delPermUser') || menuButtonPermissions.includes('permission.delPermOrg')"
                  >批量删除</el-button
                  >
                  <el-button :disabled="!queryUserListParams.orgRoleId" v-if="radio1 === 1 && menuButtonPermissions.includes('permission.addPermUser')" type="primary" @click="addUserOrOrg()" size="mini">添加用户</el-button>

                  <el-button :disabled="!queryUserListParams.orgRoleId" v-if="radio1 === 2 && menuButtonPermissions.includes('permission.addPermOrg')" type="primary" @click="addUserOrOrg()" size="mini">添加组织</el-button>
                </div>
              </div>
            </div>
            <div v-show="radio1 === 1" v-loading="userListDataLoading">
              <el-table
                ref="tableUserRef"
                :data="tableUserList"
                @selection-change="handleSelectionChange"
                row-key="id"
                stripe
                :height="tableMaxHeigth"
              >
                <el-table-column type="selection" reserve-selection align="center" width="50" />
                <el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip />
                <el-table-column prop="userName" label="用户名" align="center" show-overflow-tooltip />
                <el-table-column prop="orgName" label="机构名称" align="center" show-overflow-tooltip />
                <el-table-column prop="fullNames" label="全路径" align="center" show-overflow-tooltip />
                <el-table-column prop="roleType" label="操作" align="center" width="50" v-if="menuButtonPermissions.includes('permission.delPermUser')">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      class="table-button-size"
                      title="移除角色"
                      @click="delUser(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                :total="userTotal"
                :page.sync="queryUserListParams.pageNo"
                :limit.sync="queryUserListParams.pageSize"
                @pagination="getOrgRoleUserListData"
              />
            </div>
            <div v-show="radio1 === 2" v-loading="userListDataLoading">
              <el-table
                ref="tableOrgRef"
                :data="tableOrgList"
                row-key="id"
                stripe
                @selection-change="handleSelectionChange1"
                :height="tableMaxHeigth">
                <el-table-column type="selection" reserve-selection align="center" width="50" />
                <!-- <el-table-column prop="name" label="姓名" align="center" show-overflow-tooltip /> -->
                <!-- <el-table-column prop="userName" label="用户名" align="center" show-overflow-tooltip /> -->
                <el-table-column prop="orgName" label="机构名称" align="center" show-overflow-tooltip />
                <el-table-column prop="fullNames" label="全路径" align="center" show-overflow-tooltip />
                <el-table-column label="操作" align="center" width="50" v-if="menuButtonPermissions.includes('permission.delPermOrg')">
                  <template #default="{row}">
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      class="table-button-size"
                      title="移除组织"
                      @click="delOrg(row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                :total="orgTotal"
                :page.sync="queryOrgListParams.pageNo"
                :limit.sync="queryOrgListParams.pageSize"
                @pagination="getPermOrgListData"
              />
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <addUserDialoag
      ref="addUserDialoagRef"
      v-if="addUserDialoagFlag"
      :orgRoleId="this.queryUserListParams.orgRoleId"
      @changeStatus="changeStatus"
      @getOrgRoleUserListData="getOrgRoleUserListData"
    ></addUserDialoag>
    <addUser ref="addUserRef" @getTableList="getTableList"></addUser>
    <addOrgDialoag ref="addOrgDialoagRef" v-if="addOrgDialoagFlag" @changeOrgStatus="changeOrgStatus" :orgRoleId="queryOrgListParams.orgRoleId" @getPermOrgListData="getPermOrgListData"></addOrgDialoag>
  </div>
</template>

<script>
import orgTree from '@/views/userManage/components/orgTree'
import { getOrgRoleList, getOrgRoleUserList, delUserPerm, getPermOrgList, delPermOrg, delOrgRole } from '@/api/authorityManage'
import addUserDialoag from './components/addUserDialoag'
import addUser from './components/addUser'
import addOrgDialoag from './components/addOrgDialoag.vue'
import actions from '@/cros/actions'

export default {
  name: 'UserManage',
  components: {
    orgTree,
    addUserDialoag,
    addUser,
    addOrgDialoag
  },
  data () {
    return {
      radio1: 1,
      addUserDialoagFlag: false,
      addOrgDialoagFlag: false,
      leftOrgTreeHeight: document.body.offsetHeight - 80,
      tableMaxHeigth: 0,
      orgObj: {},
      roleTableList: [],
      roleTableListTotal: 0,
      tableList: [],
      tableUserList: [],
      tableOrgList: [],
      selectOrgList: [],
      total: 0,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        orgId: ''
      },
      queryUserListParams: {
        pageSize: 10,
        pageNo: 1,
        orgRoleId: 0,
        name: '',
        userName: ''
      },
      queryOrgListParams: {
        pageSize: 10,
        pageNo: 1,
        orgRoleId: 0
      },
      userTotal: 0,
      orgTotal: 0,
      selectUserList: [],
      menuButtonPermissions: [],
      userListDataLoading: false
    }
  },
  watch: {
    orgObj: {
      handler: function (newVal) {
        if (!newVal?.id) return
        this.queryParams.orgId = newVal.id
        this.getTableList()
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    actions.onGlobalStateChange((state, prevState) => {
      this.menuButtonPermissions = state.menuButtonPermissions.map(v => v.buttonKey)
    }, true)
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.setTableHeight)
    // 初始化表格高度
    this.setTableHeight()
  },
  methods: {
    beforeDestroy () {
      // 组件销毁前移除事件监听
      window.removeEventListener('resize', this.setTableHeight)
    },
    setTableHeight () {
      this.$nextTick(() => {
        this.tableMaxHeigth = document.body.offsetHeight / 2 - 216
      })
    },
    handleSelectionChange (val) {
      this.selectUserList = val
    },
    handleSelectionChange1 (val) {
      this.selectOrgList = val
    },
    delRole (row) {
      this.$confirm(`是否删除名称为 '${row.roleName}' 的数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delOrgRole({ orgRoleId: row.id }).then((res) => {
            if (res.code === 'success') {
              this.$message.success('操作成功')
              this.getTableList()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          console.log('取消删除')
        })
    },
    batchDelete () {
      const arrLength = this.radio1 === 1 ? this.selectUserList.length : this.selectOrgList.length
      this.$confirm(`是否删除 '${ arrLength}条' 数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.radio1 === 1 && this.menuButtonPermissions.includes('permission.delPermUser')) {
        const ids = this.selectUserList.map((v) => v.id).join(',')
        delUserPerm({ ids }).then((res) => {
        if (res.code === 'success') {
          this.$message.success('操作成功')
          this.getOrgRoleUserListData()
          this.selectUserList = []
        } else {
          this.$message.error(res.msg)
        }
        })
      } else if (this.radio1 === 2 && this.menuButtonPermissions.includes('permission.delPermOrg')) {
        const ids = this.selectOrgList.map((v) => v.id).join(',')
        delPermOrg({ ids }).then((res) => {
          if (res.code === 'success') {
            this.$message.success('操作成功')
            this.getPermOrgListData()
            this.selectOrgList = []
          } else {
            this.$message.error(res.msg)
          }
        })
      }
      this.$refs.tableOrgRef && this.$refs.tableOrgRef.clearSelection()
      this.$refs.tableUserRef && this.$refs.tableUserRef.clearSelection()
      })
      .catch(() => {
        console.log('取消删除')
      })
    },
    delOrg (row) {
      this.$confirm(`是否删除机构名称为 '${row.orgName}' 的数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.tableOrgRef && this.$refs.tableOrgRef.toggleRowSelection(row, false)
          delPermOrg({ ids: row.id }).then((res) => {
            if (res.code === 'success') {
              this.$message.success('操作成功')
              this.getPermOrgListData()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          console.log('取消删除')
        })
    },
    delUser (row) {
      this.$confirm(`是否删除名称为 '${row.name}' 的数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.tableUserRef && this.$refs.tableUserRef.toggleRowSelection(row, false)
          delUserPerm({ ids: row.id }).then((res) => {
            if (res.code === 'success') {
              this.$message.success('操作成功')
              this.getOrgRoleUserListData()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          console.log('取消删除')
        })
    },
    addUserOrOrg () {
      if (this.radio1 === 1) {
          this.addUserDialoagFlag = true
          this.$nextTick(() => {
            this.$refs.addUserDialoagRef.open()
          })
      } else {
          this.addOrgDialoagFlag = true
          this.$nextTick(() => {
            this.$refs.addOrgDialoagRef.open()
          })
        }
    },
    changeStatus () {
      this.addUserDialoagFlag = !this.addUserDialoagFlag
    },
    changeOrgStatus () {
      this.addOrgDialoagFlag = !this.addOrgDialoagFlag
    },
    searchUserList (row) {
      this.queryUserListParams.orgRoleId = row.id
      this.queryOrgListParams.orgRoleId = row.id
      this.radioGroup()
    },
    radioGroup () {
      if (!this.queryUserListParams.orgRoleId) return
      if (!this.queryOrgListParams.orgRoleId) return
      if (this.radio1 === 1) {
        this.getOrgRoleUserListData()
      } else {
        this.getPermOrgListData()
      }
      this.$nextTick(() => {
        this.selectOrgList = []
        this.selectUserList = []
        this.$refs.tableOrgRef && this.$refs.tableOrgRef.clearSelection()
        this.$refs.tableUserRef && this.$refs.tableUserRef.clearSelection()
      })
    },
    async getPermOrgListData () {
      this.userListDataLoading = true
      getPermOrgList(this.queryOrgListParams).then(res => {
        this.userListDataLoading = false
        this.tableOrgList = res.data.list
        this.orgTotal = res.data.totalCount
      }).catch(() => {
        this.userListDataLoading = false
      })
    },
     getOrgRoleUserListData () {
      this.userListDataLoading = true
       getOrgRoleUserList(this.queryUserListParams).then((res) => {
        this.userListDataLoading = false
        this.tableUserList = res.data.list
        this.userTotal = res.data.totalCount
       }).catch(() => {
        this.userListDataLoading = false
      })
    },
    addUserHandle () {
      this.$refs.addUserRef.open(this.queryParams.orgId)
    },
    resetData () {
      this.queryUserListParams.pageNo = 1
      this.queryUserListParams.pageSize = 10
      this.queryUserListParams.orgRoleId = 0
      this.tableUserList = []
      this.userTotal = 0
      this.queryOrgListParams.pageNo = 1
      this.queryOrgListParams.pageSize = 10
      this.queryOrgListParams.orgRoleId = 0
      this.tableOrgList = []
      this.orgTotal = 0
    },
    // 获取列表数据
    async getTableList () {
      this.resetData()
      const res = await getOrgRoleList(this.queryParams)
      console.log('列表数据', res)
      this.roleTableList = res.data.list
      this.roleTableListTotal = res.data.totalCount
        if (this.radio1 === 1 && this.roleTableList.length > 0) {
          this.searchUserList(this.roleTableList[0])
          this.$refs.roleTableListRef.setCurrentRow(this.roleTableList[0])
        }
        if (this.radio1 === 2 && this.roleTableList.length > 0) {
          this.searchUserList(this.roleTableList[0])
          this.$refs.roleTableListRef.setCurrentRow(this.roleTableList[0])
        }
    }
  }
}
</script>

<style lang="scss" scoped>
.leftOrgTree {
  height: calc(100vh - 60px);
  padding: 10px;
  padding-right: 0;
}

.table-block {
  margin-top: 10px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background-color: #fff;
  color: #606266;
}
</style>
